<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>翻译服务</title>
    <script>
        async function translateText() {
            try {
                // 获取 access_token
                const tokenResponse = await fetch("https://open.xjguoyu.cn/api/auth/oauth/token?grant_type=client_credentials&client_id=6d9ed85e9826e6de8b6a39cea81bba86&secret=xYXYcMmBeTDRGa6HQwPpRCieTfzbKcDZ");
                const tokenData = await tokenResponse.json();
                const accessToken = tokenData.access_token;

                if (!accessToken) {
                    console.error("未获取到 access_token");
                    alert("未获取到 access_token");
                    return;
                }

                // 发送翻译请求
                const text = document.getElementById("text").value;
                const translateResponse = await fetch("https://open.xjguoyu.cn/api/core/1.0/mt?appKey=ldxlVOlPTkF5qyKKNZxkkiBgu2qkFh47", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json;charset=utf-8",
                        "Authorization": "Bearer " + accessToken
                    },
                    body: JSON.stringify({
                        "text": text,
                        "src": "cn",
                        "to": "ug"
                    })
                });

                const result = await translateResponse.json();
                document.getElementById("result").innerText = JSON.stringify(result);
            } catch (error) {
                console.error("发生错误:", error);
                alert("发生错误: " + error.message);
            }
        }
    </script>
</head>
<body>
    <h1>翻译服务</h1>
    <p>请确保您在本地服务器上运行此页面。您可以使用以下命令启动本地服务器：</p>
    <pre>
        python -m http.server 8000
    </pre>
    <p>然后在浏览器中访问 <a href="http://localhost:8000/translate.html">http://localhost:8000/translate.html</a></p>
    <textarea id="text" rows="4" cols="50" placeholder="输入要翻译的文本"></textarea><br>
    <button id="translateButton">翻译</button>
    <h2>翻译结果:</h2>
    <pre id="result"></pre>

    <script>
        // 确保按钮点击事件正常工作
        document.getElementById("translateButton").onclick = translateText;
    </script>
</body>
</html> 